package org.epidroid.epidroid.androsoul.ui.contactlist.messagequeue;

import java.util.List;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;
import org.epidroid.epidroid.androsoul.ui.AndroSoulActivity;
import org.epidroid.epidroid.androsoul.ui.utils.TextFormater;

import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MessageQueueAdapter extends ArrayAdapter<MessageQueueItem> {

	private List<MessageQueueItem> _items;
	private AndroSoulActivity _context;

	public MessageQueueAdapter(AndroSoulActivity context,
			int textViewResourceId, List<MessageQueueItem> objects) {
		super(context, textViewResourceId, objects);
		_context = context;
		_items = objects;
	}

	private SpannableString getAuthorFormatedText(MessageQueueItem item) {
		ForegroundColorSpan fg;
		if (item.getAuthor().equals(MessageQueue.ANDROSOUL_AUTHOR))
			fg = new ForegroundColorSpan(Color.YELLOW);
		else
			fg = new ForegroundColorSpan(Color.RED);
		SpannableString ss = SpannableString.valueOf(item.getAuthor() + ": ");
		ss.setSpan(fg, 0, item.getAuthor().length() + 2, 0);
		return ss;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater inflater = (LayoutInflater) _context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.androsoul_messagequeue_item, null);
		}
		final MessageQueueItem m = this._items.get(position);

		TextView content = (TextView) v
				.findViewById(R.id.androsoul_messagequeue_item_content);
		SpannableString ss = getAuthorFormatedText(m);
		content.setText(ss);

		content.append(TextFormater.getSpannable(null, _context,
				TextFormater.reduceString(m.getContent(), 30)));
		content.setPadding(3, 0, 1, 1);

		final NetsoulContact c = m.getContact();
		if (c != null) {
			content.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					_context.launchConversation(c);
				}
			});
		}

		return (v);
	}
}
